'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 任务
 * @author sundbcn@gmail.com (sun debing)
 */

var mongoose = require('mongoose');
var _ = require('lodash');
var moment = require('moment');
var dataApi = require('../libs/dataApi');
var taskFactory = require('../libs/taskFactory');
var sevenActivityMgr = require('../mgr/sevenActivityMgr');
var dailyConf = require('../config/dailyConf');
var configUtil = require('../util/configUtil.js');

var _initTaskList = function () {
    var task_list = [];
    dataApi.open_seven_day.each(function (task_conf, task_id) {
        task_list.push(+task_id);
    });
    return task_list;
};

/**
 * 开服7天活动
 */
var sevenDayActivitySchema = new mongoose.Schema({
    // 玩家id
    role_id: {
        type: Number,
        required: true,
        unique: true,
        index: true
    },

    current_task_list: {
        type: Array,
        default: _initTaskList
    },

    // 已经完成的任务列表
    complete_task_list: [Number],

    // 已经领过取奖励的任务列表
    have_receive_list: [Number],

    // 统计的列表
    static_list: {
        type: mongoose.Schema.Types.Mixed,
        default: {}
    },

    // 上次刷新的时间
    last_refresh_time: {
        type: Date,
        default: 0
    }
});

sevenDayActivitySchema.pre('save', function (next) {
    this.increment();
    if (!this.isNew && !!this.isModified()) {
        this.pushModify();
    }
    next();
});

/**
 * 是否领取过奖励
 */
sevenDayActivitySchema.methods.isReceive = function (task_id) {
    return _.indexOf(this.have_receive_list, task_id) == -1;
};
sevenDayActivitySchema.methods.addReceiveRecord = function (task_id) {
    if (_.indexOf(this.have_receive_list, task_id) == -1) {
        this.have_receive_list.push(task_id);
    }
};

/**
 * 获取统计的列表
 */
sevenDayActivitySchema.methods.getStaticList = function (task_static_type) {
    this.static_list[task_static_type] = this.static_list[task_static_type] || {};
    return this.static_list[task_static_type];
};

sevenDayActivitySchema.methods.setChange = function () {
    this.markModified('static_list');
};

/**
 * 是否任务能够完成
 * @param  {[type]}  task_id [description]
 * @return {Boolean}         [description]
 */
sevenDayActivitySchema.methods.isTaskCanComplete = function (task_id) {
    task_id = +task_id;
    var now_value = _getTaskProgress(this.static_list, task_id);
    if (!this.isHaveTask(task_id)) {
        return false;
    }
    return now_value >= _getTaskTotalProgress(task_id);
};

/**
 * 获取当前的任务
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
sevenDayActivitySchema.methods.isHaveTask = function (task_id) {
    task_id = +task_id;
    return _.indexOf(this.current_task_list, task_id) !== -1;
};

/**
 * 获取当前的任务
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
sevenDayActivitySchema.methods.isHaveTask = function (task_id) {
    task_id = +task_id;
    return _.indexOf(this.current_task_list, task_id) !== -1;
};

/**
 * 判断任务是否完成
 * @param  {[type]}  task_id [description]
 * @return {Boolean}         [description]
 */
sevenDayActivitySchema.methods.isTaskComplete = function (task_id) {
    task_id = +task_id;
    return _.indexOf(this.complete_task_list, task_id) !== -1;
};

/**
 * 是否任务能够完成
 * @param  {[type]}  task_id [description]
 * @return {Boolean}         [description]
 */
sevenDayActivitySchema.methods.isTaskCanComplete = function (task_id) {
    task_id = +task_id;
    var now_value = _getTaskProgress(this.static_list, task_id);
    if (!this.isHaveTask(task_id)) {
        return false;
    }
    return now_value >= _getTaskTotalProgress(task_id);
};

/**
 * 获取当前的任务
 */
sevenDayActivitySchema.methods.getCurrentTaskList = function () {
    return this.current_task_list;
};

/**
 * 获取已领取过奖励任务列表
 */
sevenDayActivitySchema.methods.getHaveReceiveList = function () {
    return this.have_receive_list;
};

/**
 * 获取任务的奖励
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
sevenDayActivitySchema.methods.rewardTask = function (task_id) {
    task_id = +task_id;
    if (!this.isTaskCanComplete(task_id)) {
        return false;
    }

    // 移除任务
    this.current_task_list.pull(task_id);

    // 添加到reward的列表中
    this.complete_task_list.push(task_id);
    return true;
};

/**
 * 添加一个新任务
 * @param {[type]} task_id [description]
 */
sevenDayActivitySchema.methods.addTask = function (task_id) {
    task_id = +task_id;

    // 如果已经完成不加入
    if (!!this.isTaskComplete(task_id)) {
        return false;
    }

    var task = this.isHaveTask(task_id);
    if (!!task) {
        return false;
    }
    this.current_task_list.push(task_id);
    return true;
};

/**
 * 刷新任务
 * @return {[type]} [description]
 */
sevenDayActivitySchema.methods.refreshFollowTask = function () {
    var self = this;
    dataApi.open_seven_day.each(function (task_conf, task_id) {
        var pre_task_id = task_conf.need_id;
        if (!!self.isTaskComplete(pre_task_id)) {
            self.addTask(task_id);
        }
    });
};

/**
 * 获取统计的列表
 */
sevenDayActivitySchema.methods.getStaticList = function (task_static_type) {
    this.static_list[task_static_type] = this.static_list[task_static_type] || {};
    return this.static_list[task_static_type];
};

sevenDayActivitySchema.methods.setChange = function () {
    this.markModified('static_list');
};

/**
 * 获取修改
 * @return {[type]} [description]
 */
sevenDayActivitySchema.methods.getLastChange = function () {
    return this.toJSON();
};

/**
 * 推送给用户
 * @return {[type]} [description]
 */
sevenDayActivitySchema.methods.push = function () {
    this.pushModify();
};

sevenDayActivitySchema.methods.pushModify = function () {
    sevenActivityMgr.sendSevenDayActivityChanged(
        this.role_id,
        this.getLastChange(),
        function (err, fails) {
            if (err) {
                console.error('send daily_task message error: %j, fail ids: %j', err, fails);
                return;
            }
        }
    );
};

/**
 * 获取任务的进度
 * @param  {[type]} static_list [description]
 * @param  {[type]} task_id     [description]
 * @return {[type]}             [description]
 */
var _getTaskProgress = function (static_list, task_id) {
    static_list = static_list || {};
    var task_conf = dataApi.open_seven_day.findById(task_id);
    if (!task_conf) {
        console.error('dailyTask is can not found:' + task_id);
        return 0;
    }

    var task_type = task_conf.type;
    if (!!static_list[task_type]) {
        return taskFactory.getInstance(task_type).getProgress(static_list[task_type], task_conf) || 0;
    }
    return 0;
};

/**
 * 获取任务的总进度
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
var _getTaskTotalProgress = function (task_id) {
    var task_conf = dataApi.open_seven_day.findById(task_id);
    if (!task_conf) {
        return 0;
    }
    return task_conf.value1;
};

/**
 * 是否在开服7天活动时间
 * @param  {[type]} task_id [description]
 * @return {[type]}         [description]
 */
var _isVaildOpenTime = function (task_id) {
    var task_conf = dataApi.open_seven_day.findById(task_id);
    if (!task_conf) {
        return 0;
    }

    var end_time = configUtil.getOpenGameTime() + 7 * 86400;

    var open_time = configUtil.getOpenGameTime() + (task_conf.open_time - 1) * 86400;
    var nwo_time = moment().unix();

    if (nwo_time >= open_time && nwo_time < end_time) {
        return true;
    } else {
        return false;
    }
};

if (!sevenDayActivitySchema.options.toJSON) {
    sevenDayActivitySchema.options.toJSON = {};
}
/* jshint unused:false */
sevenDayActivitySchema.options.toJSON.transform = function (doc, ret) {

    // 处理任务进度
    var task_list = [];
    _.each(ret.current_task_list, function (task_id) {

        // 任务id对应任务是否完成   0表示没完成   1表示完成
        var state = 0;
        if (_getTaskProgress(ret.static_list, task_id) >= _getTaskTotalProgress(task_id) && !!_isVaildOpenTime(task_id)) {
            state = 1;
        }

        // 是否领取过   0没领取   1领取过
        var is_receive = 0;
        if (_.indexOf(ret.have_receive_list, task_id) !== -1) {
            is_receive = 1;
        }

        task_list.push({
            task_id: task_id,
            task_state: state,
            is_receive: is_receive,
            progress: _getTaskProgress(ret.static_list, task_id),
            total_progress: _getTaskTotalProgress(task_id)
        });
    });

    if (configUtil.getOpenGameTime() + (7 * 86400) <= moment().unix()) {
        task_list = [];
    }
    ret.current_task_list = task_list;
    delete ret.role_id;
    delete ret.complete_task_list;
    delete ret.static_list;
    delete ret.last_refresh_time;
    delete ret._id;
    delete ret.__v;
};

mongoose.model('SevenDayActivity', sevenDayActivitySchema);
